<template>
  <el-dialog
    :title="$t('main.addConnectionDialogTitle')"
    :visible.sync="connectionDialogVisible"
    width="400px"
    :before-close="closeDialog">
    <el-form ref="connectionForm" status-icon :model="connection" :rules="rules" label-width="80px">
      <el-form-item label="Host" prop="Host">
        <el-input v-model="connection.Host" :placeholder="$t('FormPlaceholder.Host')"></el-input>
      </el-form-item>
      <el-form-item label="Port" prop="Port">
        <el-input v-model="connection.Port" :placeholder="$t('FormPlaceholder.Port')"></el-input>
      </el-form-item>
      <el-form-item label="Auth" prop="Auth">
        <el-input v-model="connection.Auth" :placeholder="$t('FormPlaceholder.Auth')"></el-input>
      </el-form-item>
      <el-form-item label="Name" prop="Name">
        <el-input v-model="connection.Name" :placeholder="$t('FormPlaceholder.Name')"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="connectionMethod('connectionForm')">{{$t('FormPlaceholder.OK')}}</el-button>
        <el-button @click="closeDialog">{{$t('FormPlaceholder.cancel')}}</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import storage from '../redis/storage'
export default {
  props: {
    connectionDialogVisible: false
  },
  data () {
    var portValid = (rule, value, callback) => {
      var pattern = /^[0-9]{1,5}$/
      if (!pattern.test(value)) {
        callback(new Error(this.$t('FormPlaceholder.PortFormatError')))
      } else {
        callback()
      }
    }
    return {
      connection: {
        Host: '127.0.0.1',
        Port: '6379',
        Auth: '',
        Name: '',
        show: false,
        dbSize: 0,
        keys: [],
        total: 0,
        index: 1,
        size: 50,
        choseDb:'DB0',
        match:'',
        disbleSearch:true
      },
      rules: {
        Host: [
          { required: true, message: this.$t('FormPlaceholder.HostFormatError'), trigger: 'blur' }
        ],
        Port: [
          { validator: portValid, trigger: 'blur' }
        ],
        Name: [
          { required: true, message: this.$t('FormPlaceholder.NameFormatError'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeDialog () {
      this.$emit('close-dialogStatus')
    },
    connectionMethod (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let server=Object.assign({}, this.connection)
          if (storage.addConnection(server)) {
            this.$emit("addServers",server)
            this.closeDialog()
            this.$refs[formName].resetFields();
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
</style>